package com.fzebu.fastboot.form.converter.impl;

import com.alibaba.fastjson.JSONObject;
import com.fzebu.fastboot.form.converter.AbstractProcessHandler;
import com.fzebu.fastboot.form.exception.ConvertException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import weaver.soa.workflow.request.Cell;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.Row;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jack
 * @version 1.0.0
 * @create 2020/1/26 19:41
 */
public class ReqFormHandler extends AbstractProcessHandler {

    @Override
    public Object toJavaBean() throws ConvertException {
        int len = builder.getAliasFieldMap().size();
        JSONObject json = new JSONObject(len);
        if (!ArrayUtils.isEmpty(builder.getProperties())) {
            int count = 0;
            for (Property property : builder.getProperties()) {
                if (len == count) { break; }
                count += super.putValue(json, property.getName(), property.getValue());
            }
        }
        return super.toJavaBean(json);
    }

    @Override
    public List<Object> toJavaArray() throws ConvertException {
        int size;
        if (builder.getDetailTable() == null || (size = builder.getDetailTable().getRowCount()) == 0) {
            return new ArrayList<>(0);
        }
        JSONObject json;
        List<Object> resList = new ArrayList<>(size);
        int length = builder.getAliasFieldMap().size();
        for (Row row : builder.getDetailTable().getRow()) {
            Cell[] rowCell = row.getCell();
            int count = 0;
            json = new JSONObject(row.getCellCount());
            for (Cell cell : rowCell) {
                if (length == count) { break; }
                count += super.putValue(json, cell.getName(), cell.getValue());
            }
            resList.add(super.toJavaBean(json));
        }
        return resList;
    }
}
